<?php
require_once(OC::$SERVERROOT."/apps/resumes/lib/helper.php");
require_once(OC::$SERVERROOT."/apps/resumes/lib/resume.php");

$companyid = 0;
if(!OC_User::isLoggedIn()) {
   $app = PFactory::getApplication();
   $companyid = $app->getUserState('resumeshare_companyid', 0);
   if(!$companyid) {
      echo '您需要先登录';
      exit;
   }
} else {
   if (PFactory::isJobseekerUser()) {
      echo '您不是企业用户';
      exit();
   } else {
      $user = PFactory::getMasterUser();
      $companyid = $user->id;
   }
}

$resumeid = JRequest::getInt('resumeid', 0);

$model = new PResumesModelResume();
$jobseekerinfo=$model->getResumeJobDetail($resumeid, $companyid);
if(empty($jobseekerinfo)) {
   echo 'File Not Found';
   exit; 
}

$realname = $jobseekerinfo->attachment; 

if (empty($realname)) {
   echo 'File Not Found';
   exit; 
}

$file_type=JFile::getExt($realname); 
$file = $resumeid.'.'.$file_type;

$datadir = getUserDataDir($companyid);
$extdir = getUserExtDir($companyid);
$jobseekerinfo->storage_path = PStorage::getResumeStoragePath($jobseekerinfo->hashkey);
$resumefiles = PStorage::getResumeFilePath($companyid, $jobseekerinfo, "upload"); 

if(empty($resumefiles)) {
   echo 'File Not Found';
   exit; 
}
// resumefiles is in array list, so pick first one 
$resumefile = array_shift($resumefiles); 

$file = dirname($resumefile) . "/".$file;
if (file_exists($file)) {
   // handle content conversion 
   $finfo= finfo_open(FILEINFO_MIME_TYPE);
   $content_type = finfo_file($finfo, $file);
   finfo_close($finfo);

   $content = file_get_contents($file);

   if($content_type == 'text/html' || $content_type == 'text/plain') {
      // need to check if mht doc file 
      $file_type=JFile::getExt($file);
      if(in_array($file_type, array('doc', 'docx', 'mht')) && stripos($content, 'MIME-version:') !== FALSE) {
         // mht document 
         $content_type = 'multipart/related'; 
      }
   }

   header('Content-Type: '.$content_type.';charset=utf-8');
   
   jimport('joomla.environment.browser');
   $browser = JBrowser::getInstance();
   $userBrowser = $browser->getBrowser();
   $userAgent = $browser->getAgentString();
   
   if ($content_type != 'text/plain' && $content_type != 'text/html') {
      if ($userBrowser == 'msie' || strpos($userAgent, "Trident/") !== false) {
         header('Content-Disposition: attachment; filename="'.rawurlencode($realname).'"');
      } else {
         header('Content-Disposition: attachment; filename*=UTF-8\'\''.$realname.'; filename="'.$realname.'"');
      }
   } 
   header('Content-Length: '.strlen($content));
   echo $content;
} else {
   echo 'File Not Found';
}
